package com.acwing.lc.part1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author rkc
 * @date 2022/9/15 9:54
 */
public class LC47全排列II {

    private List<List<Integer>> ans = new ArrayList<>();
    private List<Integer> path = new ArrayList<>();
    private boolean[] st = new boolean[10];

    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        dfs(nums);
        return ans;
    }

    private void dfs(int[] nums) {
        if (path.size() == nums.length) {
            ans.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!st[i]) {
                if (i > 0 && nums[i] == nums[i - 1] && !st[i - 1]) continue;
                st[i] = true;
                path.add(nums[i]);
                dfs(nums);
                st[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }
}
